#include <iostream>
#include <string>
#include <cstring>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <unistd.h>

#include "InetAddr.hpp"

static const uint16_t default_port = 8888;
static std::string default_ip = "127.0.0.1";


// 因为是聊天室，所以对于客户端来说，要能够同时发送消息和接收消息，不能够说发送消息之后就一直等待接收消息。
// 这里使用多线程来解决这个问题, 因此接收消息和发送消息的代码要分离并用独立的函数包装
// 

class Client
{
public:
    Client(std::string& ip = default_ip, const uint16_t& port = default_port)
        :_port(port), _ip(ip)
    {}

    ~Client()
    {
        if(_sockfd > -1)
        {
            close(_sockfd);
        }
    }

    void Init()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_sockfd < 0)
        {
            std::cout << "Socket failed" << std::endl;
        }
    }

    void Send()
    {
        struct sockaddr_in sock_sever;
        memset(&sock_sever, 0, sizeof(sock_sever));
        sock_sever.sin_family = AF_INET;
        sock_sever.sin_port = htons(_port);
        sock_sever.sin_addr.s_addr = inet_addr(_ip.c_str());

        std::string meassage;
        char buffer[1024];
        while (true)
        {
            std::cout << "Pleas enter:";
            getline(std::cin, meassage);
            int n = sendto(_sockfd, meassage.c_str(), meassage.size(), 0, (const sockaddr*)&sock_sever, sizeof(sock_sever));
        }
    }
    
    void Receive()
    {
        while(true)
        {
            char buffer[1024];
            struct sockaddr_in server;
            socklen_t len = sizeof(server);
            ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer), 0, (struct sockaddr*)&server, &len);
            if(n > 0)
            {
                buffer[n] = 0;
                std::cout << buffer << std::endl;
            }
            else
            {
                std::cout << "recvfrom failed" << std::endl;
            }
        }
    }


private:
    int _sockfd;
    uint16_t _port;
    std::string _ip;
};